package com.lingnan.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lingnan.config.QiNiuCouldConfig;
import com.lingnan.mapper.ActiveMapper;
import com.lingnan.pojo.Active;
import com.lingnan.pojo.Admin;
import com.lingnan.service.ActiveService;
import com.lingnan.service.AdminService;
import com.lingnan.service.TargetService;
import com.lingnan.util.HttpRequestUtil;
import com.lingnan.util.MD5Utils;
import com.lingnan.util.Result;
import com.lingnan.util.ResultGenerator;
import com.lingnan.vo.ActiveVo;
import com.lingnan.vo.AdminVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 梁兴达整合
 * @Date 2022/3/12 17:17:06
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Value("${saveFile.path}")
    private String path; //获取yml文件路径

    @Autowired
    private AdminService adminService;
    @Autowired
    private ActiveService activeService;
    @Autowired
    private ActiveMapper activeMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private QiNiuCouldConfig qiNiuCouldConfig;

    @PostMapping("/register")
    @ApiOperation("管理员注册")
    public Result register(@ApiParam("传jobId和密码") @RequestBody Admin admin) {
        if (StrUtil.isBlank(admin.getJobId()) || StrUtil.isBlank(admin.getPassword())) {
            return ResultGenerator.genErrorResult(201, "参数错误！");
        } else
        {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("job_id",admin.getJobId());
            Admin one = adminService.getOne(queryWrapper);
            if (!ObjectUtils.isEmpty(one)){
                return ResultGenerator.genErrorResult(201, "管理员id已注册！");
            }
        else {
            adminService.registerAdmin(admin);
            if (admin.getJobId().equals(admin.getJobId())) {
                return ResultGenerator.genSuccessResult(200, "注册成功！");
            }
            return ResultGenerator.genSuccessResult(201, "注册失败！");
        }
        }
    }

    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public Result login(@ApiParam("传jobId和密码") @RequestBody AdminVo adminVo) {
        String jobId = adminVo.getJobId();
        String password = adminVo.getPassword();
        if (StrUtil.isBlank(jobId) || StrUtil.isBlank(password)) {
            return ResultGenerator.genErrorResult(201, "参数错误！");
        } else {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("job_id",adminVo.getJobId());
            wrapper.eq("password", MD5Utils.MD5Encode(adminVo.getPassword(),"UTF-8"));
            Admin one = adminService.getOne(wrapper);
            Admin admin = adminService.getById(one.getId());
            Admin login = adminService.login(admin);
            if (adminVo.getJobId().equals(jobId)) {
                return ResultGenerator.genSuccessResult(200,login, "登录成功！");
            }
            return ResultGenerator.genSuccessResult(201, "登录失败！");
        }
    }

    /**
     * 七牛云上传文件
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @ApiOperation("上传文件")
    public Result uploadFile(@ApiParam(value = "file")@RequestParam(value = "file") MultipartFile file) throws IOException {
//        if (ObjectUtils.isNotEmpty(file) && file.getSize() > 0) {//判断文件不为空和大小
//            //重命名处理  hello.jpg clo.jpeg  截取最后点之前的内容
//            String oldFileName = file.getOriginalFilename();//获取上传的原文件名
//            //获取源文件的前缀名
//            String prefix = oldFileName.substring(0, oldFileName.lastIndexOf(".")); //截取.点前面的内容
//            //获取源文件的后缀名
//            String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")); //截取.点后面的内容
//            //时间格式化格式
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//            //获取当前时间并作为时间戳
//            String timeStamp=simpleDateFormat.format(new Date());
//
//            //重命名操作
//            String newFileName = prefix +"_"+ timeStamp + suffix;
//
//            //指定文件存储位置  path/uploading
//            String dirUploadImage = path + File.separator + "/uploadFile" + File.separator + newFileName;
//            File filePath = new File(dirUploadImage);
//            //判断存储图片目录是否存在 不存在就构建 uploadImage目录
//            if (!filePath.exists()) {
//                filePath.mkdirs();
//            }
//            file.transferTo(filePath);
//            //model.addAttribute("msg",dirUploadImage);


            if (ObjectUtils.isNotNull(file) && file.getSize()>0){//判断文件不为空和大小
            //重命名处理  hello.jpg clo.jpeg  截取最后点之前的内容
            String oldFileName = file.getOriginalFilename();//获取上传的原文件名
            //获取源文件的前缀名
            String prefix = oldFileName.substring(0, oldFileName.lastIndexOf(".")); //截取.点前面的内容
            //获取源文件的后缀名
            String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")); //截取.点后面的内容
            //时间格式化格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //获取当前时间并作为时间戳
            String timeStamp=simpleDateFormat.format(new Date());

            //重命名操作
            String newFileName = prefix +"_"+ timeStamp + suffix;
            //构造流对象
            InputStream inputStream = file.getInputStream();
            String cloudUpload = qiNiuCouldConfig.uploadImageQiNiu(inputStream, newFileName);
            //把名字传回去
            return ResultGenerator.genSuccessResult(200,cloudUpload, "文件上传成功");
        } else {
            return ResultGenerator.genErrorResult(201, "文件上传失败");
        }
    }


    /**
     * 多个上传文件
     * @param files
     * @return
     */
    @PostMapping("/uploadFiles")
    public Result uploadFiles(@ApiParam(value = "files")@RequestParam(value = "files",required = false) MultipartFile[] files) throws IOException {
        if (ObjectUtils.isNotEmpty(files)){
            for (int i = 0;i<files.length;i++) {
                if (ObjectUtils.isNotEmpty(files[i]) && files[i].getSize()>0) {//判断文件不为空和大小
                    //重命名处理  hello.jpg clo.jpeg  截取最后点之前的内容
                    String oldFileName = files[i].getOriginalFilename();//获取上传的原文件名
                    //获取源文件的前缀名
                    String prefix = oldFileName.substring(0, oldFileName.lastIndexOf(".")); //截取.点前面的内容
                    //获取源文件的后缀名
                    String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")); //截取.点后面的内容
                    //时间格式化格式
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    //获取当前时间并作为时间戳
                    String timeStamp = simpleDateFormat.format(new Date());
                    //重命名操作
                    String newFileName = prefix + "_" + timeStamp + suffix;
                    //构造流对象
                    InputStream inputStream = files[i].getInputStream();
                    String cloudUpload = qiNiuCouldConfig.uploadImageQiNiu(inputStream, newFileName);
                    //把名字传回去
                    return ResultGenerator.genSuccessResult(200,cloudUpload,"文件上传成功");
                }
            }
            return ResultGenerator.genSuccessResult(200,"多个文件上传成功");

        }return ResultGenerator.genErrorResult(201,"文件上传失败");


    }



    /**
     * 发布活动
     * @param active
     * @return
     */
    @PostMapping("/releaseActive")
    @ApiOperation("发布活动")
    @Transactional
    public Result releaseActive(@ApiParam("传活动对象") @RequestBody Active active){
        if (!ObjectUtils.isEmpty(active)){
            boolean flag = activeService.publishActive(active);
            if (flag){
                return  ResultGenerator.genSuccessResult(200,"发布活动成功");
            }else {
                return ResultGenerator.genErrorResult(201,"发布活动失败");
            }
        }
        return ResultGenerator.genErrorResult(201,"发布活动失败");
    }

    /**
     * 修改活动
     * @param active
     * @return
     */
    @PostMapping("/changeActive")
    @ApiOperation("修改活动")
    public Result changeActive(@ApiParam("传活动对象")@RequestBody Active active){
        System.out.println(active);
        if (!ObjectUtils.isEmpty(active)){
            activeService.updateActive(active);
            return  ResultGenerator.genSuccessResult(200,"修改活动成功");
        }
        return ResultGenerator.genErrorResult(201,"修改活动失败");
    }

    /**
     * 已发布活动列表
     * @param
     * @return
     */
    @PostMapping("/activeList")
    @ApiOperation("已发布活动列表")
    public Result activeList(){
        QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("competition_type", "校内", "校外", "非比赛")
                    .eq("info_type", "非通知")
                    .orderByDesc("begin_time", "end_time");
        List<Active>  list = activeService.list(queryWrapper);
        if (!ObjectUtils.isEmpty(list)) {
            return ResultGenerator.genSuccessResult(200, list, "已发布活动列表展示成功");
        }
        return ResultGenerator.genErrorResult(201,"已发布活动列表展示失败");
    }

    /**
     * 活动详情展示
     * @return
     */
    @PostMapping("/activeDetail")
    @ApiOperation("活动详情展示")
    public Result activeDetail(@ApiParam("传活动id")@RequestBody ActiveVo activeVo){
        List<Active> list = null;
        if (!ObjectUtils.isEmpty(activeVo)) {
            QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", activeVo.getId());
            list = activeService.list(queryWrapper);
        }
        if (!ObjectUtils.isEmpty(list)) {
            return ResultGenerator.genSuccessResult(200, list, "活动详情展示成功");
        }
        return ResultGenerator.genErrorResult(201,"活动详情展示失败");
    }



    /**
     * 发布通知
     * @param active
     * @return
     */
    @PostMapping("/releaseNotice")
    @ApiOperation("发布通知")
    public Result releaseNotice(@ApiParam("传通知对象")@RequestBody Active active){
        if (!ObjectUtils.isEmpty(active)){
                activeService.publishActive(active);
                return  ResultGenerator.genSuccessResult(200,"发布通知成功");
        }
        return ResultGenerator.genErrorResult(201,"发布通知失败");
    }

    /**
     * 修改通知
     * @param active
     * @return
     */
    @PostMapping("/changeNotice")
    @ApiOperation("修改通知")
    public Result changeNotice(@ApiParam("传通知对象")@RequestBody Active active){
        if (!ObjectUtils.isEmpty(active)){
            activeService.updateActive(active);
            return  ResultGenerator.genSuccessResult(200,"修改通知成功");
        }
        return ResultGenerator.genErrorResult(201,"修改通知失败");
    }

    /**
     * 已发布通知列表
     * @param
     * @return
     */
    @PostMapping("/noticeList")
    @ApiOperation("已发布通知列表")
    public Result noticeList(){
        QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("competition_type", "通知")
                    .orderByDesc("begin_time", "end_time");
        List<Active> list = activeService.list(queryWrapper);
        if (!ObjectUtils.isEmpty(list)) {
            return ResultGenerator.genSuccessResult(200, list, "已发布通知列表展示成功");
        }
        return ResultGenerator.genErrorResult(201,"已发布通知列表展示失败,请登录管理员账号");
    }
    /**
     * 通知详情展示
     * @return
     */
    @PostMapping("/noticeDetail")
    @ApiOperation("通知详情展示")
    public Result noticeDetail(@ApiParam("传通知id")@RequestBody ActiveVo activeVo){

        List<Active> list = null;
        if (!ObjectUtils.isEmpty(activeVo)) {
            QueryWrapper<Active> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", activeVo.getId());
            list = activeService.list(queryWrapper);
        }
        if (!ObjectUtils.isEmpty(list)) {
            return ResultGenerator.genSuccessResult(200, list, "通知详情展示成功");
        }
        return ResultGenerator.genErrorResult(201,"通知详情展示失败,请登录管理员账号");
    }


    @PostMapping("/searchNotice")
    @ApiOperation("管理端通知搜索")
    public Result searchNotice(@RequestBody ActiveVo activeVo){
        List<Active> actives = null;
        if (!ObjectUtils.isEmpty(activeVo)){
            String name = activeVo.getName();
            actives = activeService.searchNotice(name);
        }
        if (!ObjectUtils.isEmpty(actives)) {
            return ResultGenerator.genSuccessResult(200, actives, "活动列表搜索成功");
        }
        return ResultGenerator.genErrorResult(201,"活动列表搜索失败");
    }


    @PostMapping("/searchActive")
    @ApiOperation("管理端活动搜索")
    public Result searchActive(@RequestBody ActiveVo activeVo){
        List<Active> actives = null;
        if (!ObjectUtils.isEmpty(activeVo)){
            String name = activeVo.getName();
            actives = activeService.searchActive(name);
        }
        if (!ObjectUtils.isEmpty(actives)) {
            return ResultGenerator.genSuccessResult(200, actives, "活动列表搜索成功");
        }
        return ResultGenerator.genErrorResult(201,"活动列表搜索失败");
    }


    @PostMapping("/deleteActive")
    @ApiOperation("管理端活动逻辑删除")
    public Result deleteActive(@ApiParam("管理端活动逻辑删除，传活动id")@RequestBody ActiveVo activeVo){
        Active active = null;
        if (!ObjectUtils.isEmpty(activeVo)){
            active = adminService.deleteActice(activeVo);
        }
        if (!ObjectUtils.isEmpty(active)) {
            return ResultGenerator.genSuccessResult(200, active, "逻辑删除成功");
        }
        return ResultGenerator.genErrorResult(201,"逻辑删除失败");
    }

//    @PostMapping("/restoreActive")
//    @ApiOperation("管理端活动逻辑还原")
//    public Result restoreActive(@ApiParam("管理端活动逻辑还原，传活动id")@RequestBody ActiveVo activeVo){
//        if (activeService.recoveryById(activeVo.getId()) >0) {
//            return ResultGenerator.genSuccessResult(200, "逻辑还原成功");
//        }
//        return ResultGenerator.genErrorResult(201,"逻辑还原失败");
//    }

}
